<?php

namespace app\admin\controller;

use think\Db;
use think\Request;

class Tong extends Base
{
    /**
     * 学校码展示
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [];
            
            // 活动名称
            if(isset($params['school']) && $params['school'] != ''){
                $where['school_name|ts_school_erp'] = ['like', '%' . $params['school'] . '%'];
            }
            if(isset($params['status']) && $params['status'] != ''){
                $where['ts_status'] = $params['status'];
            }
            if(isset($params['year']) && $params['year'] != ''){
                $where['ts_year'] = $params['year'];
            }
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'ts.*,school_name';
            $count = Db::table('up_tg_school')->alias('ts')
                ->join("up_school s",'ts.ts_school_erp=s.school_erp','LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_tg_school')->alias('ts')
                ->join("up_school s",'ts.ts_school_erp=s.school_erp','LEFT')
                ->where($where)
                ->order('ts_time desc')
                ->page($Nowpage,$limits)
                ->field($field)
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 新建
     * @return mixed|\think\response\Json
     */
    public function activeAdd(){
        if(Request::instance()->isPost()){
            extract(input());
            $have = Db::table('up_tg_school')
                ->where('ts_school_erp',$ts_school_erp)
                ->where('ts_year',$ts_year)
                ->where('ts_status',1)
                ->find();
            if($have){
                return json(['code' => 100, 'msg' => '此学校在当前年份已经有统购设置了']);
            }
            //
            $today = date('Y-m-d H:i:s');
            $ts_student = trim($ts_student,', ');
            $insert = [
                'ts_school_erp' => $ts_school_erp,
                'ts_year' => $ts_year,
                'ts_money' => $ts_money,
                'ts_post' => $ts_post,
                'ts_begin' => $ts_begin,
                'ts_end' => $ts_end,
                'ts_grade' => $ts_grade,
                'ts_done' => $ts_done,
                'ts_student' => $ts_student,
                'ts_time' => $today,
                'ts_update' => $today
            ];
            if($ts_student){
                $insert['ts_student'] = ',' . $ts_student . ',';
            }
            $res = Db::table('up_tg_school')->insertGetId($insert);
            if($res){
                return json(['code' => 200, 'msg' => '新建成功']);
            }else{
                return json(['code' => 100, 'msg' => '新建失败']);
            }
        }
        $schools = Db::table('up_school')->where('school_status',1)
            ->field('school_id,school_name,school_erp')->select();
        $this->assign('schools',$schools);
        return $this->fetch('tong/activeadd');
    }

    /**
     * 编辑
     * @return mixed|\think\response\Json
     */
    public function activeEdit(){
        if(Request::instance()->isPost()){
            extract(input());
            $ts_student = trim($ts_student,', ');
            $update = [
                'ts_money' => $ts_money,
                'ts_post' => $ts_post,
                'ts_begin' => $ts_begin,
                'ts_end' => $ts_end,
                'ts_grade' => $ts_grade,
                'ts_done' => $ts_done,
                'ts_student' => $ts_student,
                'ts_update' => date('Y-m-d H:i:s')
            ];
            if($ts_student){
                $update['ts_student'] = ',' . $ts_student . ',';
            }
            $res = Db::table('up_tg_school')->where('ts_id', $ts_id)->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '编辑成功']);
            }else{
                return json(['code' => 100, 'msg' => '编辑失败']);
            }
        }
        $ts_id = input('ts_id');
        $info = Db::table('up_tg_school ts')
            ->join('up_school s','ts.ts_school_erp=s.school_erp','LEFT')
            ->where('ts_id', $ts_id)
            ->field('ts.*,school_name')
            ->find();
        $info['ts_student'] = trim($info['ts_student'],',');
        $this->assign([
            'ts_id' => $ts_id,
            'info' => $info
        ]);
        return $this->fetch('tong/activeedit');
    }
    /**
     * 改状态（是否开启）
     * @author
     */
    public function changeStatus()
    {
        extract(input());
        if($num == 1){
            $data = Db::table('up_tg_school')
                ->where('ts_id',$id)
                ->find();
            $have = Db::table('up_tg_school')
                ->where('ts_school_erp',$data['ts_school_erp'])
                ->where('ts_year',$data['ts_year'])
                ->where('ts_status',1)
                ->find();
            if($have){
                return json(['code' => 100, 'msg' => '此学校在当前年份已经有统购设置了']);
            }
        }
        $res = Db::table('up_tg_school')
            ->where('ts_id',$id)
            ->update([
                'ts_status' => $num,
                'ts_update' => date('Y-m-d H:i:s')
            ]);
        if($res){
            return json(['code' => 200, 'msg' => '成功']);
        }else{
            return json(['code' => 100, 'msg' => '失败']);
        }
    }
    /**
     * 订单
     * @return mixed|\think\response\Json
     */
    public function setGoods(){
        if(Request::instance()->isPost()){
            extract(input());
            if(empty($fahuo)){
                return json(['code'=>100,'msg'=>'选择不能为空']);
            }
            Db::startTrans();
            try {
                $insert = [];
                $sgIds = [];
                $tgMoney = 0;
                $nanMoney = 0;
                $nvMoney = 0;
                $tgUpdate = [];
                foreach ($fahuo as $k => $v){
                    $value = explode('_',$v);
                    $sg_id = $value[0];
                    $sg_price = ${"price_$sg_id"};
                    $sg_num = ${"num_$sg_id"};
//                    $sg_erp = ${"erp_$sg_id"};
                    if($value[1] == 1){
//                        if(!$xia || strtolower(substr($xia,0,2)) != 'at') return json(['code'=>100,'msg'=>'夏季套装U8单号不能为空且开头必须为AT！']);
                        if(!$xia) return json(['code'=>100,'msg'=>'夏季套装U8单号不能为空！']);
                        $sg_erp = $xia;
                        $tgUpdate['ts_xia'] = $xia;
                    } else if($value[1] == 2){
                        if(!$qiu) return json(['code'=>100,'msg'=>'秋季套装U8单号不能为空！']);
                        $sg_erp = $qiu;
                        $tgUpdate['ts_qiu'] = $qiu;
                    } else if($value[1] == 3){
                        if(!$li) return json(['code'=>100,'msg'=>'礼服U8单号不能为空！']);
                        $sg_erp = $li;
                        $tgUpdate['ts_li'] = $li;
                    } else if($value[1] == 4){
                        if(!$dong) return json(['code'=>100,'msg'=>'冬季套装U8单号不能为空！']);
                        $sg_erp = $dong;
                        $tgUpdate['ts_dong'] = $dong;
                    } else if($value[1] == 5){
                        if(!$xi) return json(['code'=>100,'msg'=>'西服U8单号不能为空！']);
                        $sg_erp = $xi;
                        $tgUpdate['ts_xi'] = $xi;
                    }else{
                        return json(['code'=>100,'msg'=>'类型有误！请重试']);
                    }

                    if(round($sg_price,2) < 0){
                        return json(['code'=>100,'msg'=>'请输入正确的价格！']);
                    }
                    if((int)$sg_num < 1){
                        return json(['code'=>100,'msg'=>'请输入正确的数量！']);
                    }
                    $thisMoney = $sg_price * $sg_num;
                    $tgMoney += $thisMoney;
                    if($value[2] == 1) $nanMoney += $thisMoney;
                    if($value[2] == 2) $nvMoney += $thisMoney;
                    $insert[] = [
                        'tsl_ts_id' => $tsl_ts_id,
                        'tsl_sg_id' => $value[0],
                        'tsl_type' => $value[1],
                        'tsl_price' => $sg_price,
                        'tsl_num' => $sg_num,
                        'tsl_number' => $sg_erp,
                    ];
                    $sgIds[] = $value[0];
                }
                $num_1 = count($sgIds);
                $sgIds = array_unique($sgIds);
                $num_2 = count($sgIds);
                if($num_1 != $num_2){
                    return json(['code'=>100,'msg'=>'单个产品只能选择一个套装类型！']);
                }
                $tgUpdate['ts_boy_money'] = $nanMoney;
                $tgUpdate['ts_girl_money'] = $nvMoney;
                $tgUpdate['ts_money'] = $tgMoney;
                Db::table('up_tg_school')
                    ->where('ts_id', $tsl_ts_id)
                    ->update($tgUpdate);
                Db::table('up_tg_school_list')
                    ->where('tsl_ts_id', $tsl_ts_id)
                    ->update([
                        'tsl_del' => 2
                    ]);
                Db::table('up_tg_school_list')
                    ->insertAll($insert);
                Db::commit();
                return json(['code' => 200, 'msg' => '成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 100, 'msg' => '失败']);
            }
        }
        $sg_school_erp = input('erp');
        $sg_year = input('year');
        $tsl_ts_id = input('ts_id');
        $field = 'sg_id,sg_good_coding,sg_year,sg_sex,sg.good_price';
        $field .= ',good_name,good_thumb';
        $goods = Db::table('up_school_good')->alias('sg')
            ->join('up_goods g','sg.sg_good_coding=g.good_coding','LEFT')
            ->where('sg_school_erp',$sg_school_erp)
            ->where('sg_year',$sg_year)
            ->order('sg_status asc')
            ->field($field)
            ->select();
        $haves = Db::table('up_tg_school_list')
            ->where('tsl_ts_id',$tsl_ts_id)
            ->where('tsl_del',1)
            ->column('concat(tsl_sg_id,"_",tsl_type)');
        //------------------------------------------------------------
        $sgIds = Db::table('up_tg_school_list')
            ->where('tsl_ts_id',$tsl_ts_id)
            ->where('tsl_del',1)
            ->order('tsl_id asc')
            ->column('tsl_sg_id');
        $sgPrices = Db::table('up_tg_school_list')
            ->where('tsl_ts_id',$tsl_ts_id)
            ->where('tsl_del',1)
            ->order('tsl_id asc')
            ->column('tsl_price');
        $sgNums = Db::table('up_tg_school_list')
            ->where('tsl_ts_id',$tsl_ts_id)
            ->where('tsl_del',1)
            ->order('tsl_id asc')
            ->column('tsl_num');
//        $sgErps = Db::table('up_tg_school_list')
//            ->where('tsl_ts_id',$tsl_ts_id)
//            ->where('tsl_del',1)
//            ->order('tsl_id asc')
//            ->column('tsl_number');
        $priceArray = array_combine($sgIds,$sgPrices);
        $numArray = array_combine($sgIds,$sgNums);
//        $erpArray = array_combine($sgIds,$sgErps);
        $this->assign('priceArray',$priceArray);
        $this->assign('numArray',$numArray);
//        $this->assign('erpArray',$erpArray);
        //---------------------------------------------------------------
        $this->assign('goods',$goods);
        $this->assign('haves',$haves);
        $this->assign('tsl_ts_id',$tsl_ts_id);
        //---------------
        $fiveNums = Db::table('up_tg_school')
            ->where('ts_id', $tsl_ts_id)
            ->find();
        $this->assign('fiveNums',$fiveNums);
        return $this->fetch('set_goods');
    }
    /**
     * 删除
     * @return \think\response\Json
     */
    public function orderdel(){
        $active_id = input('id');
        $res = Db::table('up_offline_tgorder')->where('id', $active_id)->delete();
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
    /**
     * 审核
     * @return mixed|\think\response\Json
     */
    public function shenhe(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [];
            $where['yes'] = 1;
            // 活动名称
            if(isset($params['school']) && $params['school'] != ''){
                $where['school'] = ['like', '%' . $params['school'] . '%'];
            }
            if(isset($params['type']) && $params['type'] != ''){
                $where['usetype'] = $params['type'];
            }

            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('offline_tg')->where($where)->count();// 获取总条数
            $lists = Db::name('offline_tg')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('time desc')
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    /**
     * 同意
     * @return \think\response\Json
     */
    public function yesyes(){
        $active_id = input('id');
        $res = Db::table('up_offline_tg')->where('id', $active_id)->setField('yes',2);
        if($res){
            return json(['code' => 200, 'msg' => '成功']);
        }else{
            return json(['code' => 100, 'msg' => '失败，请重试']);
        }
    }
    /**
     * 拒绝
     * @return \think\response\Json
     */
    public function nono(){
        $active_id = input('id');
        $res = Db::table('up_offline_tg')->where('id', $active_id)->setField('yes',3);
        if($res){
            return json(['code' => 200, 'msg' => '成功']);
        }else{
            return json(['code' => 100, 'msg' => '失败，请重试']);
        }
    }
    /**
     * 导出Excel
     * @return \think\response\Json
     */
    public function excelwater(){
        set_time_limit(0);
        $params = input('param.');
        $where = [];
        // 活动名称
        if(isset($params['school']) && $params['school'] != ''){
            $where['school|orderno|name|idcard|backno'] = ['like', '%' . $params['school'] . '%'];
        }
        // 状态
        if(isset($params['o_status']) && $params['o_status'] != ''){
            $where['status'] = $params['o_status'];
        }
        if(isset($params['type']) && $params['type'] != ''){
            $where['fromtype'] = $params['type'];
        }
        $field = [
            'orderno','backno','school','grade','class','name','sex','idcard',
            'height','weight','size','sw_j','sw_x',
            'sw_y','sw_t','sw_b','sw_k',
            'phone', 'fromtype','type','status','money',
            'time'
        ];
        $data = Db::name('offline_tgorder')
            ->where($where)
            ->field($field)
            ->order('time desc')
            ->select();
        if($data){
            $cellname = [
                '订单号', '支付流水号', '学校', '年级', '班级', '学生姓名', '学生性别', '入学年份',
                '身高', '体重', '衣服尺码', '三围/肩宽', '三围/胸围',
                '三围/腰围', '三围/臀围', '三围/臂长', '三围/裤长',
                '注册手机', '记录类型', '支付类型', '订单状态', '支付金额',
                '支付时间'
            ];
            $status = ['status','fromtype','type'];
            $values = [
                'status' => ['1' => '未支付','2' => '已支付'],
                'fromtype' => ['1' => '仅收集','2' => '仅支付','3' => '收集兼支付'],
                'type' => ['1' => '微信','2' => '支付宝']
            ];
            $res = exportExcel('payonline',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
}